import { Form, Input, Card, message } from "antd";
import React, { useState, useEffect } from "react";
import "./index.scss";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { list, getFileNameUUID, put, signatureUrl, del } from "../../../utils/oss";
import CardCoverItem from "../../../components/CardCoverItem";
import { HeaderFormCom, PaginationCom } from "../../../components/ArticleDetailCom/DrawerMultilayer/OssFileDrawer";
import { DraggerLoader } from "../posterAdmin";
import FileDrawerItem from "../../../components/FileDrawerItem";
function FileAdmin() {
  const [fileList, setFileList] = useState([]);
  const [fileName, setFileName] = useState("");
  const [fileType, setFileType] = useState("");
  const [pIndex, setPageIndex] = useState(1);
  const [pSize, setPageSize] = useState(8);
  const [total, setTotal] = useState(0);
  const [handlerData, setHandlerData] = useState([]);
  const [visible, setVisible] = useState(false);
  const [info, setInfo] = useState({});
  useEffect(() => {
    init();
  }, []);
  const init = () => {
    getOssFileList();
  };
  const handleUpload = async (option) => {
    NProgress.start();
    // // 获取文件的后缀名
    var obj = option.file.name;
    var index = obj.lastIndexOf(".");
    obj = obj.substring(index, obj.length);
    // 生成的文件名，保留文件后缀名，进行拼接
    let objName = getFileNameUUID() + option.file.name;
    // 调用 ali-oss 中的方法,flieName是存放的文件夹名称，可自己定义
    await put(`flieName/${objName}`, option.file).then(() => {
      // console.log(res);
      message.success("上传成功");
      // 上传成功之后，转换真实的地址
      signatureUrl(`flieName/${objName}`).then((res) => {});
    });
    await NProgress.done();
    init();
  };
  //获取数据
  const getOssFileList = async (pageIndex = 1, pageSize = 8) => {
    NProgress.start();
    let { objects } = await list();
    setHandlerData([...objects]);
    setTotal(objects.length);
    objects = objects.map((item) => {
      return {
        ...item,
        fileType: item.name.split(".")[1],
      };
    });
    objects = objects.filter((item) => {
      return item.name.includes(fileName) && item.fileType.includes(fileType);
    });
    objects.sort((a, b) => {
      return new Date(b.lastModified) - new Date(a.lastModified);
    });
    objects = objects.slice((pageIndex - 1) * pageSize, pageSize * pageIndex);
    await setFileList([...objects]);
    NProgress.done();
  };
  const handlerFileList = async (pageIndex = 1, pageSize = 8) => {
    let newList = JSON.parse(JSON.stringify(handlerData));
    newList = newList.map((item) => {
      return {
        ...item,
        fileType: item.name.split(".")[1],
      };
    });
    newList = newList.filter((item) => {
      return item.name.includes(fileName) && item.fileType.includes(fileType);
    });
    setTotal(newList.length);
    newList.sort((a, b) => {
      return new Date(b.lastModified) - new Date(a.lastModified);
    });
    newList = newList.slice((pageIndex - 1) * pageSize, pageSize * pageIndex);
    await setFileList([...newList]);
  };
  const changePagination = (pageIndex, pageSize) => {
    setPageSize(pageSize);
    setPageIndex(pageIndex);
    handlerFileList(pageIndex, pageSize);
  };
  //重置
  const resetForm = () => {
    setFileName("");
    setFileType("");
  };
  //关闭弹框
  const closeVisible = () => {
    setVisible(false);
  };
  const openVisible = async (info) => {
    await setInfo({ ...info });
    setVisible(true);
  };
  const delOssFileList = async (name) => {
    await del(name);
    await init();
    await closeVisible();
    message.success("删除成功");
  };
  return (
    <div className="file-admin">
      <div>
        <DraggerLoader handleUpload={handleUpload}></DraggerLoader>
      </div>
      <Card>
        <HeaderFormCom
          className="header-form-com"
          getOssFileList={getOssFileList}
          handlerSearchBtn={() => {
            setPageIndex(1);
            handlerFileList(1, pSize);
          }}
          handlerResetBtn={resetForm}
        >
          <Form layout="inline">
            <Form.Item label="文件名">
              <Input
                placeholder="请输入文件名"
                value={fileName}
                onChange={(e) => {
                  setFileName(e.target.value);
                }}
              />
            </Form.Item>
            <Form.Item label="文件类型">
              <Input
                placeholder="请输入文件类型"
                value={fileType}
                onChange={(e) => {
                  setFileType(e.target.value);
                }}
              />
            </Form.Item>
          </Form>
        </HeaderFormCom>
      </Card>
      <Card>
        <div className="oss-file-wrapper">
          {fileList.map((item, index) => (
            <CardCoverItem
              info={item}
              key={index}
              cover={<img src={item.url} />}
              title={item.name.split("flieName/")[1]}
              handlerType="url"
              isClickImg
              handlerInfoClick={() => {
                openVisible(item);
              }}
            ></CardCoverItem>
          ))}
        </div>
        <div className="oss-file-pagination">
          <PaginationCom total={total} pageSize={pSize} pageIndex={pIndex} onChange={changePagination} />
        </div>
      </Card>
      <FileDrawerItem visible={visible} closeVisible={closeVisible} info={info} handlerClickDel={delOssFileList}></FileDrawerItem>
    </div>
  );
}
export default FileAdmin;
